package controllers;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import controllers.CRUD.ObjectType;

import models.Book;
import models.BookType;
import models.Comment;
import play.Play;
import play.db.Model;
import play.exceptions.TemplateNotFoundException;
import play.mvc.Controller;
import play.mvc.With;
import service.BookTypeService;
import util.FileUtil;
import util.ImageUtil;
import util.ResourceOperate;
import util.Util;

@With(Secure.class)
@CRUD.For(Book.class)
public class Bookaction  extends CRUD {
	
	@Check("BookManage")
    public static void list(int page, String search, String searchFields, String orderBy, String order) {
        ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        if (page < 1) {
            page = 1;
        }
        List<Model> objects = type.findPage(page, search, searchFields, orderBy, order, (String) request.args.get("where"));
        Long count = type.count(search, searchFields, (String) request.args.get("where"));
        Long totalCount = type.count(null, null, (String) request.args.get("where"));
        try {
            render(type, objects, count, totalCount, page, orderBy, order);
        } catch (TemplateNotFoundException e) {
            render("CRUD/list.html", type, objects, count, totalCount, page, orderBy, order);
        }
    }
	
	public static void pint(File upload){
		FileInputStream fis;
		try {
			fis = new FileInputStream(upload);
			HSSFWorkbook wb = new HSSFWorkbook(new POIFSFileSystem(fis));
			HSSFSheet sh = wb.getSheetAt(0);
			int rows = sh.getLastRowNum() + 1 - sh.getFirstRowNum();
			for (int i = 1; i < rows; i++) {
				HSSFRow row = sh.getRow(i);
				int cols = row.getLastCellNum() + 1 - row.getFirstCellNum(); // 该行的总列数
				for (int j = 0; j < 6; j++) {
					HSSFCell col = row.getCell((short) j);
					System.err.println(col.getCellType());
				}
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		render();
	}
	
	public static void show_book(Long booId){
		List<BookType> bookTypes = null;/*一级分类--关联下级*/
		bookTypes = BookType.find("fid is null").fetch();
		//给当前分类加载子集分类
		List<BookType> newTypes = new ArrayList<BookType>();
		for(int i = 0 ; i < bookTypes.size() ;i ++){
			BookType b = bookTypes.get(i);
			b = BookType.setSun(b);
			newTypes.add(b);
		}
		
		Book boo = Book.findById(booId);
		render("/Bookaction/book.html",boo,bookTypes);
	}
	
	public static void action(){
		render();
	}
	
	public static void comment(String tit,String cen,String lev,Long booid){
		String str="";
		Comment com = new Comment();
		com.comTime = new Date();
		com.comTit = tit;
		com.comDet = cen;
		com.xj = Double.parseDouble(lev);
		com.memId = Long.parseLong(session.get("userid"));
		com.boolId = booid;
		try{
		com.save();
		str = "评论成功!";
		}catch(Exception e){
			str = "评论失败";
		}
		render("/BookTypeaction/table.json",str);
	}
	
	//装载分类,跳转到添加页
	public static void blank(){
		List<BookType> list = BookTypeService.getFtall(null);
        render("/Bookaction/blank.html",list);
	}
	
	public static void save(File file,Book book){
		try{
			String[] types = {"jpg","jpeg","png","gif"};
				System.err.println("%%%%%%%%%%%%%%%%%%%%%%%");
				//日期文件夹
				Calendar ca = Calendar.getInstance();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
				String dir = sdf.format(ca.getTime());
				//上传路径
				String type = FileUtil.getFileExtName(file.getName());
				String uploadPath = "/public/upload/"+ dir+"/"+dir+"_"+Util.uuid2()+type;
				File fileBig = Play.getFile(uploadPath);
				book.bimage = uploadPath;
				try {
					FileUtils.copyFile(file, fileBig);
					fileBig.mkdirs();
					
					try {
						BufferedImage srcBufferedImage = ImageIO.read(file);
						ImageUtil.zoom(srcBufferedImage, file, 105, 150);
					} catch (IOException e) {
						e.printStackTrace();
					}
					
					String uploadPath_sm = "/public/upload/"+ dir+"/"+dir+"_"+Util.uuid2()+"_sm"+type;
					File fileSm = Play.getFile(uploadPath_sm);
					FileUtils.copyFile(file, fileSm);
					book.simage = uploadPath_sm;
				} catch (IOException e) {
					System.err.println("%%%%%%%%%文件操作%%%%%%%%%%%%%%");
				}
		}catch(Exception e){System.err.println("%%%%%%%%%file is null%%%%%%%%%%%%%%");}
			
			try{
				book._save();
				flash.success("图书添加成功!");
				redirect(request.controller + ".show", book._key());
			}catch(Exception e){
				flash.error("图书添加成功!");
			}
		System.err.println("%%%%%%%%%%%%%%%%%%%%%%%");
	}
}
